package com.example.mqttmodule.service;

import lombok.extern.log4j.Log4j2;
import org.dromara.mica.mqtt.spring.server.MqttServerTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

@Service
@Log4j2
public class PublishService {

    /**
     * 服务端发着消息，不支持有用户名和密码认证的服务端，auth=false
     */
    @Autowired
    private MqttServerTemplate server;



    public boolean publish(String topic,String message) throws Exception {
        try {
            boolean send = server.publishAll(topic , message.getBytes(StandardCharsets.UTF_8));
            if (!send) {
                throw new Exception("Message send timeout");
            }else {
                log.info(topic + " Message sent: " + message);
            }
        }catch (Exception e) {
            log.error("Failed to send message", e);
            throw new Exception("Failed to send message" + e.getMessage(),e);
        }
        return true;
    }
}
